package net.easymvc.core;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DownloadServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 3760587517760474675L;

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		File file = null;
		try {
			String filePath = request.getServletPath();
			String[] ss = filePath.split("\\.");
			filePath = ss[0] + "/";
			
			//获得请求文件名  
			String fileName = request.getParameter("fileName");  
			response.reset();
			//设置文件MIME类型  
			response.setContentType(getServletContext().getMimeType(fileName));  
			//设置Content-Disposition  
			response.setHeader("Content-Disposition", "attachment;filename="+fileName);  
			//读取目标文件，通过response将目标文件写到客户端  
			//获取目标文件的绝对路径  
			String fullFileName = getServletContext().getRealPath(filePath + fileName);  
			//System.out.println(fullFileName);  
			//读取文件  
			file = new File(fullFileName);
			InputStream in = new FileInputStream(file);
			OutputStream out = response.getOutputStream();  
			
			//写文件  
			int b;  
			while((b=in.read())!= -1)  
			{  
				out.write(b);  
			}  
			
			in.close();  
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			String delete = request.getParameter("delete");
			if(delete == null)return;
			if(delete.equals("1")){
				System.gc();//清理垃圾
				//TODO LOGGER
				file.delete();
			}
		}
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

	}

}
